package cn.edu.mju.dal.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.mju.dal.ICourseDAO;
import cn.edu.mju.db.DbHelper;
import cn.edu.mju.model.Course;
import cn.edu.mju.utils.Pager;

public class CourseDAO implements ICourseDAO{

	@Override
	public void save(Course c) {
		Session session = DbHelper.getSession();
		Transaction ts = session.beginTransaction();
		if(c.getcId() != null && c.getcId() > 0)
		{
			session.update(c);
		}
		else
		{
			session.save(c);
		}
		ts.commit();
		session.close();
	}

	@Override
	public void delete(Integer cId) {
		Session session = DbHelper.getSession();
		Transaction ts = session.beginTransaction();
		Course course = session.get(Course.class, cId);
		session.delete(course);
		ts.commit();
		session.close();
		
	}

	@Override
	public Pager findPager(Integer page, Course c) {
		Session session = DbHelper.getSession();		
		String hqlTotal = "select count(*) from Course where 1=1";
		String hqlSelect = "from Course order by cId desc";
				
		StringBuffer hqlWhere = new StringBuffer("");    //UserGroup类名
		if(c.getcName() != null && !"".equals(c.getcName()))
		{
			hqlWhere.append("and cName like :cName ");
		}		
		Query query = session.createQuery(hqlTotal + hqlWhere.toString());
		
		if(c != null && c.getcName() != null && !"".equals(c.getcName()))
		{
			query.setString("cName","%" + c.getcName() + "%");
		}
		
		int rows = ((Long) query.getSingleResult()).intValue();		//条数
		Pager pager = new Pager();			//实例化翻页的方法 （调用Pager方法）
		pager.setRows(rows);
		pager.setPage(page);
		
		query = session.createQuery(hqlSelect + hqlWhere.toString());	//查询UserGroup数据,显示在列表
		if(c.getcName() != null && !"".equals(c.getcName()))
		{
			query.setString("cName","%" + c.getcName() + "%");
		}
		query.setFirstResult((pager.getPage()-1)* pager.getPageSize());
		query.setMaxResults(pager.getPageSize());
		pager.setData(query.list());
		//pager.getPages();
		session.close();
		return pager;
	}

	@Override
	public Course findById(Integer cId) {
		Session session = DbHelper.getSession();
		String hql = "from Course where cId=:cId";
		Query query = session.createQuery(hql);
		query.setInteger("cId", cId);
		Course course = (Course) query.getSingleResult();
		session.close();
		return course;
	}

	@Override
	public List<Course> findAll(Course c) {
		Session session = DbHelper.getSession();
		String hql = new String("from Course where 1=1");
		Query query = session.createQuery(hql);
		List<Course> list = query.list();
		return list;
	}

}
